<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.id"
        placeholder="店铺ID"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-input
        v-model="listQuery.storeName"
        placeholder="店铺名"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-input
        v-model="listQuery.username"
        placeholder="账号名"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-document" @click="dialogExcelVisible=true">
        导入
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      border
      :data="list"
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="ID" prop="id" min-width="20%" align="center">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" min-width="20" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="账号名" min-width="16%" align="center">
        <template slot-scope="{row}">
          <span>{{ row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总金额" min-width="15%" align="center">
        <template slot-scope="{row}">
          <span>{{ row.score / 100 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="已用金额" min-width="15%" align="center">
        <template slot-scope="{row}">
          <span>{{ row.used_score / 100 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="本地商品" min-width="14%" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button size="mini" type="success" @click="showGoods(row)">
            跳转
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <el-dialog :visible.sync="dialogExcelVisible" style="width:1500px;" title="批量导入店铺">
      <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
      <span slot="footer" class="dialog-footer">
        <el-link type="primary" target="_blank" :href="storesTemplateLink">下载模板</el-link>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { parseTime } from '@/utils'
import { fetchList, importExcel, setLoop } from '@/api/store'
import { addScore } from '@/api/score'
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { Message } from 'element-ui'

export default {
  name: 'Store',
  components: { Pagination, UploadExcelComponent },
  data() {
    return {
      dialogExcelVisible: false,
      listLoading: false,
      total: 0,
      list: [],
      listQuery: {
        page: 1,
        limit: 20,
        username: '',
        storeName: '',
        id: undefined
      },
      storesTemplateLink: `${process.env.VUE_APP_BASE_API}/xlsxtemplates/storeTemplate.xlsx`
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.list.map(item => {
          item.create_time = item.create_time ? parseTime(item.create_time) : '-'
          item.update_time = item.update_time ? parseTime(item.update_time) : '-'
          return item
        })
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() { this.getList() },
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) { return true }
      this.$message({
        message: '不能上传超过1M的文件',
        type: 'warning'
      })
      return false
    },
    handleSuccess({ results, header }) {
      if (header[0] === '店铺ID' && header[1] === '店铺名称') {
        for (let i = 0; i < results.length; i++) {
          const id = results[i]['店铺ID']
          if (!/^\d+$/.test(id)) {
            Message.error(`${id}不是存数字,请修改后重新导入`)
            return
          }
          if (`${id}`.length !== 9) {
            Message.error(`${id}不是9位,请修改后重新导入`)
            return
          }
        }
        importExcel(results).then(response => {
          Message.success('导入成功')
          this.getList()
          this.dialogExcelVisible = false
        })
      } else {
        Message({
          message: '请使用模板',
          type: 'error',
          duration: 5 * 1000
        })
      }
    },
    showGoods(row) {
      this.$router.push({ name: 'Goods', query: { store_id: row.id }})
    },
    toggleLoop(row) {
      setLoop(row.id, row.loop).then(response => Message.success('设置成功'))
    },
    addScore(row) {
      this.$prompt('请输入上分数', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^\d+$/,
        inputErrorMessage: '只能输入数字'
      }).then(({ value }) => {
        addScore(row.id, value).then(_ => {
          Message.success('上分成功')
          this.getList()
        })
      }).catch((e) => {
        console.log(e)
        this.$message({
          type: 'info',
          message: '取消输入'
        })
      })
    }
  }
}
</script>

<style scoped>

</style>
